package menu_api

import (
	"benkendSystem/database"
	"benkendSystem/models"
	"github.com/gin-gonic/gin"
	"net/http"
)

// GetChildrenMenu 获取子菜单
func GetChildrenMenu(parentId int64, allMenus []*AllMenu) []*MenuReply {
	data := make([]*MenuReply, 0)
	for _, v := range allMenus {
		if v.ParentID == parentId {
			data = append(data, &MenuReply{
				ID:            v.ID,
				Name:          v.Name,
				Icon:          v.Icon,
				Order:         v.Order,
				Path:          v.Path,
				Level:         v.Level,
				ParentID:      v.ParentID,
				ComponentName: v.ComponentName,
				SubMenus:      GetChildrenMenu(v.ID, allMenus),
			})
		}
	}
	return data
}

// AllMenuToMenuReply 生成树形菜单
func AllMenuToMenuReply(allMenus []*AllMenu) []*MenuReply {
	reply := make([]*MenuReply, 0)
	for _, v := range allMenus {
		if v.ParentID == 0 {
			reply = append(reply, &MenuReply{
				ID:            v.ID,
				Name:          v.Name,
				Icon:          v.Icon,
				Order:         v.Order,
				Path:          v.Path,
				Level:         v.Level,
				ParentID:      v.ParentID,
				ComponentName: v.ComponentName,
				SubMenus:      GetChildrenMenu(v.ID, allMenus),
			})
		}
	}
	return reply
}

// Menus 获取菜单列表
func Menus(c *gin.Context) {
	data := make([]*MenuReply, 0)
	allMenus := make([]*AllMenu, 0)
	tx := database.DB.Model(new(models.Menu)).Select("id,parent_id, component_name,name,icon,`order`,path,level").Where("deleted_flag != 1").Order("`order` ASC")
	err := tx.Find(&allMenus).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "系统错误",
		})
		return
	}
	data = AllMenuToMenuReply(allMenus)
	c.JSON(http.StatusOK, gin.H{
		"code":   200,
		"msg":    "操作成功",
		"result": data,
	})
}

// GetMenuList 获取菜单列表
func GetMenuList(c *gin.Context) {
	Menus(c)
}
